#!/usr/bin/env python
#coding: utf-8

'''
Copyright (c) <2011> Ray

Permission is hereby granted, free of charge,
to any person obtaining a copy of this software
and associated documentation files (the "Software"),
to deal in the Software without restriction,
including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission 
notice shall be included in all copies or substantial
portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS",
WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''

import logging
import webapp2
from datetime import datetime, tzinfo, timedelta
from random import choice
from google.appengine.api import mail
from google.appengine.api import app_identity
from google.appengine.api import memcache

class UTC(tzinfo):
    def __init__(self, offset=0):
        self._offset = offset
    
    def utcoffset(self, dt):
        return timedelta(hours=self._offset)
        
    def tzname(self, dt):
        return "UTC +%s" % self._offset
        
    def dst(self, dt):
        return timedelta(hours=self._offset)

def HowManyMails():
    mails = memcache.get('mails')
    if mails:
        return mails
    else:
        return 0

def IBecameFamous():
    if memcache.incr('mails') == None:
        memcache.add('mails', 0)
        memcache.incr('mails')

def HowManyTimes():
    times = memcache.get('worktimes')
    if times:
        return times
    else:
        return 0

def IWorkHard():
    if memcache.incr('worktimes') == None:
        memcache.add('worktimes', 0)
        memcache.incr('worktimes')

#生成一个随机的邮件地址
def CreateMailAddress(tz):
    #YYYYMMDDhhmm + 随机三个字母
    date_output = datetime.now(UTC(int(tz))).strftime('%Y%m%d%H%M')
    rnd_suffix = ''.join([choice('abcdefghijklmnopqrstuvwxyz') for i in range(3)])
    host_name = app_identity.get_application_id() + '.appspotmail.com'
    ofm_addr = date_output + rnd_suffix + '@' + host_name
    IWorkHard()
    return ofm_addr

#把一对邮件地址队放入内存缓存
def CreateMailPair(ofm_addr, your_mail):
    if memcache.add(ofm_addr, your_mail, 1800):
        pass
    else:
        logging.debug('CreateMailPair Failed!')
    
#从内存缓存中删除一对邮件地址对
def RemoveMailPair(ofm_addr):
    if memcache.delete(ofm_addr):
        pass
    else:
        logging.debug('Delete MailPair Failed!')

#从内存缓存中读取邮件地址对
def GetMailPair(ofm_addr):
    your_mail = memcache.get(ofm_addr)
    if  your_mail == None:
        logging.debug('GetMailPair Failed! May be expired.')
    else:
        return your_mail

#处理邮件
class MailHandler(webapp2.RequestHandler):
    def post(self):
        IBecameFamous()
        mail_message = mail.InboundEmailMessage(self.request.body)
        org_sender = mail_message.sender
        ofm_addr = mail_message.to
        your_mail = GetMailPair(ofm_addr)
        if mail.is_email_valid(your_mail):
            mail.send_mail(org_sender + '<' + ofm_addr + '>', your_mail, mail_message.subject, mail_message.body)

#处理根目录请求
class RootHandler(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write(u'''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>即用即扔的电子邮件</title>
<script type="text/javascript">
function gettz() {
var d = new Date()
var tz = -d.getTimezoneOffset()/60;
return tz
}
</script>
</head>
<body>
<h1>欢迎使用One Off Mail</h1>
<p>在这里填入你的邮箱地址：</p>
<form id="email_form" action="/" method="post" onsubmit="this.tz.value=gettz()">
<input name="tz" type="hidden" value="">
<input name="email" type="email">
<input type="submit">
</form>
<br>
<p>One Off Mail 已工作 %d 次。收到了 %d 封信件。</p>
<p>One Off Mail 是开源程序。</p>
<p>源代码托管于<a href="https://code.google.com/p/one-off-mail/">Google Code</a></p>
<br>
<img src="http://code.google.com/appengine/images/appengine-noborder-120x30.gif" 
alt="Powered by Google App Engine" />
</body>
</html>''' % (HowManyTimes(), HowManyMails()))
    def post(self):
        your_mail = self.request.POST['email']
        timezone = self.request.POST['tz']
        if your_mail:
            ofm = CreateMailAddress(timezone)
            CreateMailPair(ofm, your_mail)
            self.response.headers['Content-Type'] = 'text/html'
            self.response.write(u'''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>即用即扔的电子邮件</title>
</head>
<body>
<h1>欢迎使用One Off Mail</h1>
<p>从现在起，<strike>10</strike>30分钟内发送给 %s 的邮件将会转发到 %s 。</p>
<br>
<img src="http://code.google.com/appengine/images/appengine-noborder-120x30.gif" 
alt="Powered by Google App Engine" />
</body>
</html>''' % (ofm, your_mail))
        else:
            logging.debug('Recive wrong post data.')

app = webapp2.WSGIApplication([('/', RootHandler),
                               ('/_ah/mail/[0-9]{12}[a-z]{3}@' + app_identity.get_application_id() + '\.appspotmail\.com', MailHandler)],
                               debug=True)
